/*
###############################################################################################
#                                                                                             # 
# The Page is used for Registering Site Users from the Admin Control Panel. This Page is      #
# created inside the Admin Control Panel and only the Administrator has a right to Add        #
# the new Site Users.                                                                         #
# The data will be used from the tbl_Users table                                              #
#     Author : Jaspal Mehta                                                                   #
#     Dated  : 16-Feb-2006                                                                    #
#                                                                                             #
###############################################################################################
*/

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SiteManager;

public partial class Admin_Ad_Adduser : System.Web.UI.Page
{
    //Create an Object of Manager which is defined in the namespace SiteManager
    Manager mgr = new Manager(true,"ConnectionString");
    public int id = 0;
    public string path = "";
    protected void Page_Load(object sender, EventArgs e)
    {
         try
        {
            id = Convert.ToInt32(Request.QueryString["id"]);
        }
        catch { id = 0; }
        //Label1 will be responsible to show the message whether the User is adding a new
        // User or Editing a Site user.
        ViewState["id"] = id;
        Label1.Font.Bold = true;
        Label1.ForeColor = System.Drawing.Color.Black;
        Label1.Text = id == 0 ? "Add Site User" : "Edit Site User";


        if (!IsPostBack)
        {
            //Function called 
            fillBirthYearDdl();
            FillCombos(id);
            
           
        }
    }

    /// <summary>
    /// this function fills up all the drop downs
    /// </summary>
    /// <param name="id"></param>
    public void FillCombos(int id)
    {
          

        mgr.BindList("select countrycode,countryname from tbl_country", "countryname", "countrycode", combocountryid, "select");
        mgr.BindList("select secquestion,sno from tbl_secquestions", "secquestion", "sno", combosecretquestion, "select");
     //   mgr.BindList("select healthcplan,sno from tbl_healthcplan", "healthcplan", "sno", combohealthplan, "select");
         mgr.BindList("select id,name from tbl_InsuranceCompanies", "name", "Id", combohealthplan, "select");
        //Edit a Site Users info
        if (id > 0)
        {
            // Create an Object of Recordset i.e Dataset 
            DataSet ds = mgr.ExecuteQuery("select * from tbl_Users where  isdelete=0 and id=" + id, "tbl_Users");
            if (ds.Tables[0].Rows.Count > 0)
            {
                txtfirstname.Text = ds.Tables[0].Rows[0]["fName"].ToString();
                txtmiddlename.Text = ds.Tables[0].Rows[0]["MName"].ToString();
                txtlastname.Text = ds.Tables[0].Rows[0]["LName"].ToString();
                txtemail.Text = ds.Tables[0].Rows[0]["Email"].ToString();
                txtpswd.Text = ds.Tables[0].Rows[0]["Password"].ToString();
                txtconfirmpswd.Text = ds.Tables[0].Rows[0]["Password"].ToString();
                txtaddress1.Text = ds.Tables[0].Rows[0]["Address1"].ToString();

                txtaddress2.Text = ds.Tables[0].Rows[0]["Address2"].ToString();

                txtcity.Text = ds.Tables[0].Rows[0]["City"].ToString();
                txtzipcode.Text = ds.Tables[0].Rows[0]["ZipCode"].ToString();
                txtstate.Text = ds.Tables[0].Rows[0]["State"].ToString();
                txtbirthdate.Text = ds.Tables[0].Rows[0]["birthdate"].ToString();
                txtnickname.Text = ds.Tables[0].Rows[0]["NickName"].ToString();
                txtsecretanswer.Text = ds.Tables[0].Rows[0]["SecurityAns"].ToString();
                string birthYear = ds.Tables[0].Rows[0]["BirthYear"].ToString().Trim();
              
                string hplan = ds.Tables[0].Rows[0]["Healthcplan"].ToString().Trim();

                string gndr = ds.Tables[0].Rows[0]["Gender"].ToString().Trim();
                string fsecquest = ds.Tables[0].Rows[0]["Securityques"].ToString().Trim();
                string Countryid = ds.Tables[0].Rows[0]["Countryid"].ToString().Trim();
                
                try
                {
                    combocountryid.SelectedValue = Countryid;
                    combogender.SelectedValue = gndr;

                    ddlBirthYear.SelectedValue = birthYear;
                    combosecretquestion.SelectedValue = fsecquest;
                    combohealthplan.SelectedValue = hplan;
                    
                }
                // If any Exception occurs like if a System throws any exception at the 
                // time of running a query than it will be caught by the Mother class of 
                // Exception i.e 'Throwable'for which object has been created with a name of 'ex'.
                catch 
                {
                  //  Response.Write(ex.ToString());
                }
                
            }
            
            else
            {
                Label2.Visible = true;
                Label2.ForeColor = System.Drawing.Color.Red;
                Label2.Text = "No Records found!!";
                return;
            }
        }

    }



    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Label2.Text = "";
        //checking for duplicate email when inserting a new record                  
        string sql = "";

        int id = (int)ViewState["id"];
        
        if (id == 0)
            sql = "select count(*) from tbl_Users where Email='" + txtemail.Text + "' and  isDelete=0 ";
        else
        {
            sql = "select count(*) from tbl_Users where Email='" + txtemail.Text + "' and id<>" + id + " and  isDelete=0 ";
        }

        DataSet dsEmail = mgr.ExecuteQuery(sql, "tbl1");
        if (dsEmail.Tables[0].Rows.Count > 0)
        {
            if (Convert.ToInt32(dsEmail.Tables[0].Rows[0][0].ToString()) > 0)
            {
                Label2.Visible = true;
                Label2.ForeColor = System.Drawing.Color.Red;
                Label2.Text = "Email already exists!! Please try with a different email id.";

                return;
            }
        }
        // end checking for duplicate email 

        
        //Retrieving All the Values of Forms in the Variables
        string tFName = txtfirstname.Text.Replace("'", "''").Trim();
        string tMName = txtmiddlename.Text.Replace("'", "''").Trim();
        string tLName = txtlastname.Text.Replace("'", "''").Trim();
        string temail = txtemail.Text.Replace("'", "''").Trim();
        string tpswd = txtpswd.Text.Replace("'", "''").Trim();
        string taddr1 = txtaddress1.Text.Replace("'", "''").Trim();
        string taddr2 = txtaddress2.Text.Replace("'", "''").Trim();
        string tcity = txtcity.Text.Replace("'", "''").Trim();
        string tzipcode = txtzipcode.Text.Replace("'", "''").Trim();
        string tstate = txtstate.Text.Replace("'", "''").Trim();
        string tcountry = combocountryid.SelectedItem.Value.ToString().Trim();
        string bdate = txtbirthdate.Text.Replace("'", "''").Trim();
        string birthYear = ddlBirthYear.SelectedItem.Text.Trim();
        string gender = combogender.SelectedItem.Value.ToString().Trim();
        string hcplan = combohealthplan.SelectedItem.Value.ToString().Trim();
        string secques = combosecretquestion.SelectedItem.Value.ToString().Trim();
        string tsecans = txtsecretanswer.Text.Replace("'", "''").Trim();
        string tnicknm = txtnickname.Text.Replace("'", "''").Trim();
        DateTime tregdt = DateTime.Now;
        
               
        string sqlQuery = "";
        if (id > 0)
        {
            //Update Site User Query
            sqlQuery = "Update tbl_Users set fName='" + tFName + "',MName='" + tMName + "',LName='";
            sqlQuery += tLName + "',Email='" + temail + "',Password = '" + tpswd + "',Address1='";
            sqlQuery += taddr1 + "',Address2='" + taddr2 + "',City='" + tcity + "',ZipCode='";
            sqlQuery += tzipcode + "',State='" + tstate + "',CountryId='" + tcountry + "',BirthDate='" + bdate + "',BirthYear='" + birthYear + "',Gender='" + gender + "',HealthCPlan='" + hcplan + "',SecurityQues='" + secques + "',SecurityAns='" + tsecans + "',NickName='" + tnicknm + "' where Id=" + id;
            Response.Write ("query" + sqlQuery);
        }
        else
        {
            //Insert Site User Query
            sqlQuery = "insert into tbl_Users(fName,MName,LName,";
            sqlQuery += "Email,Password,Address1,Address2,City,ZipCode,State,CountryId";
            sqlQuery += ",RegDate,BirthDate,BirthYear,Gender,HealthCPlan,SecurityQues,SecurityAns,NickName)values('";
            sqlQuery += tFName + "','" + tMName + "','" + tLName + "','" + temail + "','" + tpswd + "','" + taddr1 + "','" + taddr2 + "','" + tcity + "','" + tzipcode + "','" + tstate + "','" + tcountry + "','" + tregdt + "','" + bdate + "','" + birthYear + "','" + gender+ "','" + hcplan + "','" + secques + "','" + tsecans + "','" + tnicknm + "')";
            Response.Write("New User Added Successfully !!");
        }
           try
                {
                    mgr.ExecuteQuery(sqlQuery);
                    //If Query is successfull the User will be redirected to the main page
                    Response.Redirect("Ad_ManageSiteUsers.aspx");                    
                }
                   // If any Exception occurs like if a System throws any exception at the 
                   // time of running a query than it will be caught by the Mother class of 
                   // Exception i.e 'Throwable'for which object has been created with a name of 'es'.
                catch (Exception es)
                {
                    Response.Write(es.ToString());
                    Label2.Visible = true;
                    Label2.Font.Bold = true;
                    Label2.ForeColor = System.Drawing.Color.Red  ;
                    Label2.Text = es.ToString();
                }

    }
    private void fillBirthYearDdl()
    {
        for (int i = (DateTime.Today.Year - 6); i > 1910; i--)
            ddlBirthYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
        ddlBirthYear.Items.Insert(0, new ListItem("--Select--", ""));
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        int id = (int)ViewState["id"];
        //If Cancel button is clicked than the user will be redirected to the main page.
        if (id > 0)
            Response.Redirect("ad_managesiteusers.aspx");
        else
            Response.Redirect("ADadminAccess.aspx"); 
    }
}
